package zooin.net;

import java.io.BufferedInputStream;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.ImageView.ScaleType;

public class ViewVideo extends Activity {
	public AimsHandover hanover = new AimsHandover();
    private String filename;
    private String vposition;
    public int cposition;
    public static String INTENT_VAL ="";
	protected String vodID;
	protected String viewType;
	public function fc = new function();
	private SharedPreferences pref =null;
	public String html;
	private String pUserIdx, thisIP, thisM , dMode;
	
    ArrayAdapter<String> Adapter;

	ArrayList<String> arDeviceIDList = new ArrayList<String>();
	ArrayList<String> arDeviceTypeList = new ArrayList<String>();
	ArrayList<String> arDeviceMessage = new ArrayList<String>();
	
	
    int mSelect =0;

      VideoView vv = null;
      @Override
      public void onCreate(Bundle savedInstanceState) {    
    	  super.onCreate(savedInstanceState);
            setContentView(R.layout.video);
            //System.gc();

            pref    = getSharedPreferences("userInfo",Activity.MODE_PRIVATE);
            SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
    	         pUserIdx 	= prefs.getString("pUserIdx", "");
    	         thisIP 	= prefs.getString("thisIP", "");
    	         thisM 		= prefs.getString("thisM", "");
    	         dMode		= prefs.getString("dMode", ""); 

            Intent i = getIntent();
            
            Bundle extras = i.getExtras();
            filename = extras.getString("videofilename");
            vposition = extras.getString("videoposition");
            viewType = extras.getString("videotype");
            vodID = extras.getString("videoid");
            
            if(dMode=="dm"){
            	Toast.makeText(ViewVideo.this, filename, Toast.LENGTH_LONG).show();
             }

            /*            
             ProgressDialog 생성 */
    		final ProgressDialog progDialog = new ProgressDialog(this);
    		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    		progDialog.setMessage("잠시만 기다려주세요....");
    		progDialog.show();

    /* VideoView생성 및 uri가져오기 */
    		vv = (VideoView) findViewById(R.id.video);
    		final MediaController mc = new MediaController(ViewVideo.this);
    		mc.setAnchorView(vv);
    		vv.setMediaController(mc);
   
    		vv.setOnErrorListener(new OnErrorListener() {
				
				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					Toast.makeText(ViewVideo.this, "재생할수 없는 컨텐츠입니다", Toast.LENGTH_LONG).show();
					ViewVideo.this.finish();
					return false;
				}
			});
    		
    		
    		vv.setVideoPath(filename);
    		vv.requestFocus();
    		

    /* VideoView의 로딩완료시 이벤트 발생 */ 
  
 		vv.setOnPreparedListener(new OnPreparedListener() {
    			
    			@Override
    			public void onPrepared(MediaPlayer mp) {
    				 /*  	 로딩 후에 할일 */
    				vv.start();
    				vv.seekTo(Integer.parseInt(vposition));
    				progDialog.dismiss();
    				
    			}
    			
    		});
 	
      }
      
      //매뉴 만들기
      public boolean onCreateOptionsMenu(Menu menu) {
      	boolean result = super.onCreateOptionsMenu(menu);
      		MenuInflater menuInflator = new MenuInflater(this);
      		menuInflator.inflate(R.menu.player_setting, menu);
      	return result;
      }
      //menu 이벤트처리
      public boolean onOptionsItemSelected(MenuItem item){
    	  if(pUserIdx==""| pUserIdx==null){
  			// Toast.makeText(ViewVideo.this, "arDeviceTypeList : "+arDeviceTypeList, Toast.LENGTH_LONG).show();
		      	switch (item.getItemId()) {
		      	case R.id.handover:
			        Toast.makeText(ViewVideo.this, "핸드오버호출1", Toast.LENGTH_SHORT).show();
					hanover.sendHOMessage();
			        Toast.makeText(ViewVideo.this, "핸드오버호출2", Toast.LENGTH_SHORT).show();
			        
					return true;
					
				/// 장면 전화 메뉴 버튼 눌렀을때 실행되는 부분	
		   		case R.id.nscreen:	
		   		 Toast.makeText(ViewVideo.this, "로그인 후 사용하세요", Toast.LENGTH_LONG).show();
		   			return true;
		      	}	
		   	
 			}else{
						ArrayAdapter<String> deviceAdapter;
						deviceAdapter =callDeviceIdx();
						String[] itemlist = arDeviceTypeList.toString().replace("[", "").replace("]", "").split(",");
						
						// Toast.makeText(ViewVideo.this, "arDeviceTypeList : "+arDeviceTypeList, Toast.LENGTH_LONG).show();
				      	switch (item.getItemId()) {
				      	case R.id.handover:
				      		
					        Toast.makeText(ViewVideo.this, "핸드오버호출1", Toast.LENGTH_SHORT).show();
							hanover.sendHOMessage();
					        Toast.makeText(ViewVideo.this, "핸드오버호출2", Toast.LENGTH_SHORT).show();
					        
							return true;
							
						/// 장면 전화 메뉴 버튼 눌렀을때 실행되는 부분	
				   		case R.id.nscreen:	
				   			
				   				new AlertDialog.Builder(ViewVideo.this).setTitle(arDeviceMessage.get(0)).setItems(itemlist,new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										mSelect = which;
										String deviceIdx = arDeviceIDList.get(mSelect);
										String call4000;
									  	call4000 = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=4000&deviceIdx="+deviceIdx+"&viewType="+viewType.trim()+"&contentID="+vodID+"&position="+vv.getCurrentPosition(),ViewVideo.this);
										//Toast.makeText(ViewVideo.this, call4000, Toast.LENGTH_LONG).show();
									  	vv.stopPlayback();
									  	ViewVideo.this.finish();						
										
									}
								}).setNegativeButton("취소", null).show();  
				   			}
      	}
      	return (super.onOptionsItemSelected(item));
      }
   
      ////재생 전환을 위한  fuction
      //2004번호출 useridx-->'device_idx'.'device_name''device_type
      public ArrayAdapter<String> callDeviceIdx() {

    		Intent intent = getIntent();
    		
        	String intentVal=intent.getExtras().getString(INTENT_VAL);
	    		vodID=intentVal.split(",")[0]; 	
	    		viewType=intentVal.split(",")[1]; 	
	    		
            SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
    	         pUserIdx 		= prefs.getString("pUserIdx", "");
    	         thisIP 		= prefs.getString("thisIP", "");
    	        
    	         
  
			///////////////////////////////////////// 
	     //   Toast.makeText(ViewVideo.this, "viewType : "+viewType, Toast.LENGTH_LONG).show();
	     //   Toast.makeText(ViewVideo.this, "postUserIdx : "+postUserIdx, Toast.LENGTH_LONG).show();
			String call2004;
			call2004 = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=2004&useridx="+ pUserIdx +"&deviceType="+thisM,this);
			int deviceCnt = Integer.parseInt(call2004.split("ú")[0]);	
			String[] htmlRow,htmlCol,device_idx,device_type;
			htmlRow =  call2004.split("ú");
			int rowLen = htmlRow.length-1;
			String typeL,idL, message;
			arDeviceIDList.clear();
			arDeviceTypeList.clear();
  			for (int i = 1; i < rowLen; i++) {
  				htmlCol = htmlRow[i].split("");
  				typeL=htmlCol[2];
  				
  				if(!typeL.equals(thisM)){	
  				idL=htmlCol[0];
  				arDeviceIDList.add(idL);  				
	           // Toast.makeText(ViewVideo.this, "device_idx : "+htmlCol[0], Toast.LENGTH_SHORT).show();
	          //  Toast.makeText(ViewVideo.this, "device_name 이름 : "+typeL, Toast.LENGTH_SHORT).show();
	        //    Toast.makeText(ViewVideo.this,"device_type : "+htmlCol[2], Toast.LENGTH_SHORT).show();
  				
  					if ( typeL.toString().equals("MO") )
  					{
  						typeL="Mobile";
  					}
  					if ( typeL.toString().equals("ST") )
  					{
  						typeL="STB";
  					}
  					if ( typeL.toString().equals("TA") )
  					{
  						typeL="TABLET";
  					}
  					arDeviceTypeList.add(typeL);
  				}
  				
  				if(rowLen > 2){	
  					message="재생전환";
  					arDeviceMessage.add(message); 	  				
  	  			}else{

  					message="전환할 기기없음";
  					arDeviceMessage.add(message); 	
  	  			}
  				
  			}
  		//	Toast.makeText(ViewVideo.this,"device_type : "+arDeviceTypeList.get(0), Toast.LENGTH_SHORT).show();
  			Adapter = new ArrayAdapter<String>(ViewVideo.this,android.R.layout.simple_list_item_1, arDeviceTypeList);
  			
  			return Adapter;
  	}

       
      @Override
      public void onBackPressed() {
    	  	vv.stopPlayback();
  			ViewVideo.this.finish();
  	  }

   
}